//
//  MainViewController.swift
//  TinyShopKeeper
//
//  Created by rimi on 16/5/25.
//  Copyright © 2016年 yuying. All rights reserved.
//

import UIKit

class MainViewController: UIViewController ,UITableViewDataSource,UITableViewDelegate{

    @IBOutlet weak var leftTableView: UITableView!
    //MARK:--
    @IBOutlet weak var homeLeadingConstraint: NSLayoutConstraint!//约束
    var isShowLeft:Bool = false
    var panGuesturer:UIPanGestureRecognizer?
    //侧边数据
    let datasourceOfLeft = [["icon":"lv_input@2x.png","title":"进货管理"],["icon":"lv_output@2x.png","title":"销货管理"],["icon":"lv_store@2x.png","title":"库存管理"],["icon":"lv_cost@2x.png","title":"成本分析"]]
    
    
    //MARK: -InitData
    
    var nextSource:[[String:AnyObject]] = [[String:AnyObject]]()
    
    func initDataSource()
    {
        if self.nextSource.count > 0{
            return
        }
        //进货
        let inputSource:[String:AnyObject] = ["title":"存","datasource":[]]
        
        //销货
        let dic1:[String:String] = ["imageName":"hourTime.png","title":"时段收入分析","leftTitle":"计时统计","rightTitle":"种类统计","imageArrowName":"op_red.png","class":"sugueIdOfInCome"]//sugueIdOfInCome
        let dic2:[String:String] = ["imageName":"dailyBusiness.png","title":"日常运营分析","leftTitle":"销售额统计","rightTitle":"人均消费","imageArrowName":"op_blue.png","class":"类名,者故事模版ID,segueID"]
        
        let dic3:[String:String] = ["imageName":"shopBusiness.png","title":"商品运营分析","leftTitle":"销售额统计","rightTitle":"种类统计","imageArrowName":"op_yellow.png","class":"类名,者故事模版ID,segueID"]
        let dic4:[String:String] = ["imageName":"memberMessage.png","title":"会员信息","leftTitle":"历史消费单","rightTitle":"总消费","imageArrowName":"op_green.png","class":"sugueId4"]//sugueId4
        let dic5:[String:String] = ["imageName":"historyRecord.png","title":"历史记录","leftTitle":"历史额统计","rightTitle":"总收入","imageArrowName":"op_purple.png","class":"sugueIdOfHistory"]//sugueIdOfHistory
        var array = [[String:String]]()
        array.append(dic1)
        array.append(dic2)
        array.append(dic3)
        array.append(dic4)
        array.append(dic5)
        
        let outputSource:[String:AnyObject] = ["title":"销","datasource":array]
        //商品运营
        let goodsSource:[String:AnyObject] = ["title":"存","datasource":[]]
        
        //成本分析
        let balanceSource:[String:AnyObject] = ["title":"成本","datasource":[]]
        self.nextSource.append(inputSource)
        self.nextSource.append(outputSource)
        self.nextSource.append(goodsSource)
        self.nextSource.append(balanceSource)
        
        
        
    }
    
    
    //点击事件
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        //将首页的数据传入 并且 刷新数据'
        self .loadData(indexPath.row)//数据
    }
    
    //数据传入
    func loadData(index:Int){
        let homeVc = self.childViewControllers[0].childViewControllers[0] as! HomeViewController
        //主控制器的第一个子控制器（导航控制器）的第一个子控制器（主页）
        //将数据传入（属性传值）
        let dic:[String:AnyObject] = self.nextSource[index]
        homeVc.datasource = dic["datasource"] as![[String:String]]
        homeVc.subfixString = dic["title"] as! String
        
        //刷新界面
        homeVc.refreshData()//也是调用home里面的方法
        
    }
    
    
    //登录成功
    func loginSuccess(){
        //需要显示相应的数据~相当于点击了销货管理 默认选中了销货管理
        self.leftTableView .selectRowAtIndexPath(NSIndexPath(forRow:1,inSection: 0), animated: false, scrollPosition: UITableViewScrollPosition.None)
        
        self .loadData(1)
        
        
    }
    
 
    
    
    
    
    //MARL:-- LifeCycle生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        self.leftTableView.estimatedRowHeight = 60
        self.leftTableView.rowHeight = 60

        self.initDataSource()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
       
    }
    
    //MARK:--代理LeftTabelViewCell,UITableViewDataSource,UITableViewDelegate
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
         return 1
    }
   
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("LeftTableViewCell", forIndexPath: indexPath) as! LeftTableViewCell
        let dic:[String:String] = datasourceOfLeft[indexPath.row]
        cell.leftTableViewCellOfLabel.text = dic["title"]
        cell.leftTableViewCellOfImage.image = imageByName(dic["icon"]!)
        return cell
    }
    
    
    
    
    
    
    
    
    
    //MARK:-- 注销方法由HomeVc调用
    func logOut(){

//        
        //从storyboard里面获取 登录界面
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("LoginViewController")
        
        //添加子控制器
        self.addChildViewController(vc!)
        self.view .addSubview((vc?.view)!)
        vc?.didMoveToParentViewController(self)
        

       
    }
    
    
   
    //MARK:-- Action显隐时的动画
    func showLeftOrHidden(){
        
        //A.属性x = B.属性y * 倍数m + 常量C
        //home.left = main.left * 1 + 0 = 0 * 1 + 0
        //home.left = 常量C~~~constant
        
        if self.isShowLeft {
            //如果左侧抽屉展开，就关闭
            self.homeLeadingConstraint.constant = 0
            
        }else{
            //如果左侧抽屉没有展开，就展开
            self.homeLeadingConstraint.constant = CGRectGetWidth(UIScreen.mainScreen().bounds) * 0.6 + 10//要加上一定长度，可用于阴影
            
        }
        //动画,delay延时
        UIView.animateWithDuration(1, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
            
            //这是给约束的设置的动画，a的约束的动画要用a的父视图来更新a 
            self.view .layoutIfNeeded()
            
            
            }) { (Bool) -> Void in
                
                //改变标记
                self.isShowLeft = !self.isShowLeft
                //判断
                if self.isShowLeft {
                    //当前抽屉已经展开，创建添加手势
                    self.panGuesturer = UIPanGestureRecognizer(target:self, action:"panGesturerHandel:")
                    self.view .addGestureRecognizer(self.panGuesturer!)
                    
                }else{
                    //当前抽屉关闭
                    self.view .removeGestureRecognizer(self.panGuesturer!)
                }
        
        }
    }

    
    //MARK:--手势方法
    
    func panGesturerHandel(panGesturer:UIPanGestureRecognizer){
        //手势结束的距离
        let currrnPoiny = panGuesturer?.translationInView(self.view)
        let maxX = CGRectGetWidth((UIScreen.mainScreen().bounds)) * 0.6 + 10
        var desX = self.homeLeadingConstraint.constant + (currrnPoiny?.x)!
        
        
        
        if panGuesturer?.state == UIGestureRecognizerState.Ended{ //手势结束时
           
            //调整抽屉的伪装
            if desX < maxX / 2{
                desX = 0
            }else{
                desX = maxX
            }
            self.homeLeadingConstraint.constant = desX
            //动画,delay延时
            UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
                //这是给约束的设置的动画，a的约束的动画要用a的父视图来更新a
                self.view .layoutIfNeeded()
                }) { (Bool) -> Void in
                    
                    if desX == 0{
                        //当前抽屉从打开到关闭
                        //手势移除
                        self.isShowLeft = false
                        self.view .removeGestureRecognizer(self.panGuesturer!)
                    }
            }
   
        }else{ //手势拖动过程中
         
            if desX < 0{
                desX = 0
            }else if desX > maxX {
                desX = maxX
            }
            
            self.homeLeadingConstraint.constant = desX
            self.view.layoutIfNeeded()
        }
        
        // 手势位置重置为0,0
        self.panGuesturer?.setTranslation(CGPointZero, inView: self.view)
        
    }

    

    
    
    
}
